package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.atguigu.gulimall.product.service.CategoryBrandRelationService;
import com.atguigu.gulimall.product.vo.Catelog2Vo;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.CategoryEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    //    @Autowired
//    CategoryDao categoryDao;
    @Autowired
    RedissonClient redisson;
    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        //1.查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);

        //2.组装成父子的树形结构

        //2. 1)找到1级分类 id对应的是0,说明是1级分类
        List<CategoryEntity> level1Menus = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChildren(getChildrens(menu, entities));
            return menu; //把当前菜单改了之后重新返回再收集成List
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return level1Menus;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        //TODO //1.检查当前删除的菜单，是否被别的地方引用

        //逻辑删除
        baseMapper.deleteBatchIds(asList);
    }

    //[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> paths = new ArrayList<>();
        List<Long> parentPath = findParentPath(catelogId, paths);

        Collections.reverse(parentPath);

        return (Long[]) parentPath.toArray(new Long[parentPath.size()]);
    }

    /**
     * CacheEvict:失效模式
     * 级联更新所有的数据
     *
     * @param category
     */
//    @Caching(evict = {
//            @CacheEvict(value = "category",key = "'getLevelOneCategorys'"),
//            @CacheEvict(value = "category",key = "'catalogJSON'")
//    })
    @CacheEvict(value = "category",allEntries = true)//删除category分区下的所有数据
    @Transactional
    @Override
    public void updateCascade(CategoryEntity category) {

        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());

    }

    /**
     * getLevelOneCategorys查询所有1级分类
     *当前代码方法的结果需要缓存，如果缓存中有，不调用。没有则会调用，查出的真实数据放到缓存
     * 指定缓存名字value
     * 指定生成的key 接收一个spEL表达式
     * 指定缓存时间 配置文件中修改ttl
     * 作为json格式保存
     * @return
     */
    @Override
    @Cacheable(value = {"category"},key = "#root.method.name",sync = true)
    public List<CategoryEntity> getLevelOneCategorys() {
        System.out.println("getLeveOneCategorys.");
        List<CategoryEntity> categoryEntities = this.baseMapper.selectList(new QueryWrapper<CategoryEntity>()
                .eq("parent_cid", 0));
        return categoryEntities;
    }

    @Override
    @Cacheable(value = {"category"},key = "#root.method.name")
    public Map<String, List<Catelog2Vo>> catalogJSON() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);
        //查询所有1级分类
        List<CategoryEntity> levelOneCategorys = getParent_cid(selectList, 0L);
        //封装1级分类
        Map<String, List<Catelog2Vo>> parent_cid = levelOneCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //拿到了 每个的1级分类，查2级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());//把父id作为检索
            //封装上面的结果,封装成指定格式
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //寻找三级分类ID
                    List<CategoryEntity> categoryThree = getParent_cid(selectList, l2.getCatId());
                    //封装成指定的Vo
                    if (categoryThree != null) {
                        List<Catelog2Vo.catalog3Vo> collect = categoryThree.stream().map(l3 -> {
                            Catelog2Vo.catalog3Vo catalog3Vo = new Catelog2Vo.catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));

        return parent_cid;
    }

    public Map<String, List<Catelog2Vo>> catalogJSON2() {
        /**
         * 1.空结果缓存 解决缓存穿透的问题
         * 2.设置过期时间+随机值，解决缓存雪崩问题
         * 3.加锁，缓存击穿问题
         */
        //缓存中放JSON字符串，拿出的时候逆转成对象类型 (序列化，反序列化过程)
        //缓存编写逻辑
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //为空，缓存中没有数据，查询数据库
            Map<String, List<Catelog2Vo>> catalogJSONFromDB = catalogJSONFromDBWithRedissonLock();
            //查到的数据再放入缓存 对象转换为JSON放在缓存中
            String s = JSON.toJSONString(catalogJSONFromDB);
            stringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
            return catalogJSONFromDB;
        }
        //转为指定的对象
        Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
        });
        return result;
    }

    /**
     * redisson做分布式锁 缓存中的数据如何和数据库保持一致，缓存数据一致性问题
     * 1.双写模式 容易产生脏数据 解决：（1加锁 (2容忍时间 最终一致性
     * 2.失效模式
     * 最终一致性解决方案：1.缓存的所有数据都有过期时间，有脏数据也能触发主动更新
     *                 2.读写数据的时候，加上分布式读写锁(经常读写肯定有极大影响，但是偶尔写一次，读N次，不会有影响)
     *                  读（无所状态）有写锁的状态下才需要等待
     *
     */
    public Map<String, List<Catelog2Vo>> catalogJSONFromDBWithRedissonLock() {
        //占取分布式锁
        RLock lock = redisson.getLock("catalogJson-lock");
        lock.lock();
        Map<String, List<Catelog2Vo>> dataFromDB;
        try {
            dataFromDB = getDataFromDB();
        } finally {
            lock.unlock();
        }
        return dataFromDB;
    }

    /**
     * 分布式锁的方式
     *
     * @return
     */
    public Map<String, List<Catelog2Vo>> catalogJSONFromDBWithRedisLock() {
        String uuid = UUID.randomUUID().toString();
        //抢占分布式锁，去redis占坑
        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            //加锁成功
            //设置过期时间必须和加锁同步进行，原子性操作
//            stringRedisTemplate.expire("lock",30,TimeUnit.SECONDS);//30秒后自动删除
            Map<String, List<Catelog2Vo>> dataFromDB;
            try {
                dataFromDB = getDataFromDB();
            } finally {
                //原子性操作删锁
                String scrpit = "if redis.call('get',KEYS[1] == ARGV[1] then return redis.call('del',KEYS[1]) else retrun 0 end)";
                Long lock1 = stringRedisTemplate.execute(new DefaultRedisScript<Long>(scrpit, Long.class),
                        Arrays.asList("lock"), uuid);
            }
            return dataFromDB;
        } else {
            try {
                Thread.sleep(200);
            } catch (Exception e) {

            }
            //没成功，加锁失败，等待100ms重新获取分布式锁，重试
            return catalogJSONFromDBWithRedisLock(); //自旋方式
        }
    }

    private Map<String, List<Catelog2Vo>> getDataFromDB() {
        String catalogJSON = stringRedisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //如果缓存不为空则 直接返回结果
            //转为指定的对象
            Map<String, List<Catelog2Vo>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catelog2Vo>>>() {
            });
            return result;
        }
        /**
         *将数据库的多次查询变为1次
         */
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //查询所有1级分类
        List<CategoryEntity> levelOneCategorys = getParent_cid(selectList, 0L);
        //封装1级分类
        Map<String, List<Catelog2Vo>> parent_cid = levelOneCategorys.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //拿到了 每个的1级分类，查2级分类
            List<CategoryEntity> categoryEntities = getParent_cid(selectList, v.getCatId());//把父id作为检索
            //封装上面的结果,封装成指定格式
            List<Catelog2Vo> catelog2Vos = null;
            if (categoryEntities != null) {
                catelog2Vos = categoryEntities.stream().map(l2 -> {
                    Catelog2Vo catelog2Vo = new Catelog2Vo(v.getCatId().toString(), null, l2.getCatId().toString(), l2.getName());
                    //寻找三级分类ID
                    List<CategoryEntity> categoryThree = getParent_cid(selectList, l2.getCatId());
                    //封装成指定的Vo
                    if (categoryThree != null) {
                        List<Catelog2Vo.catalog3Vo> collect = categoryThree.stream().map(l3 -> {
                            Catelog2Vo.catalog3Vo catalog3Vo = new Catelog2Vo.catalog3Vo(l2.getCatId().toString(), l3.getCatId().toString(), l3.getName());
                            return catalog3Vo;
                        }).collect(Collectors.toList());
                        catelog2Vo.setCatalog3List(collect);
                    }
                    return catelog2Vo;
                }).collect(Collectors.toList());
            }
            return catelog2Vos;
        }));
        //查到的数据再放入缓存 对象转换为JSON放在缓存中
        String s = JSON.toJSONString(parent_cid);
        stringRedisTemplate.opsForValue().set("catalogJSON", s, 1, TimeUnit.DAYS);
        return parent_cid;
    }


    //从数据库查询并封装整个分类数据 本地锁的方式
    public Map<String, List<Catelog2Vo>> catalogJSONFromDBWithLocalLock() {

        //只要同1把锁，就能锁住需要锁的所有线程
        /**
         * 1.当前对象加锁  this springBoot流程->所有的组件在容器中都是单例的，所以即使100W并发进来，调用这个方法
         * 他也只有一个实例对象，this相当于100W个请求同时用1个this，所以肯定锁住了。非分布式的情况
         */
        synchronized (this) {
            //得到锁后，应该再去缓存中确定一次，如果没，才需要继续查询
            return getDataFromDB();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
//        return baseMapper.selectList(new QueryWrapper<CategoryEntity>()
//                .eq("parent_cid", v.getCatId()));
        List<CategoryEntity> collect = selectList.stream().filter(item -> item.getParentCid() == parent_cid).collect(Collectors.toList());
        return collect;
    }


    //225,25,2
    private List<Long> findParentPath(Long catelogId, List<Long> paths) {
        //找到父亲的ID收集过来
        paths.add(catelogId);
        //查出当前ID分类详情
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(byId.getParentCid(), paths);
        }
        return paths;
    }

    //获取每个菜单的子菜单
    //递归查找所有菜单的子菜单
    private List<CategoryEntity> getChildrens(CategoryEntity root,
                                              List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream().filter(categoryEntity -> {
            return categoryEntity.getParentCid() == root.getCatId();
        }).map(categoryEntity -> {
            //找到子菜单
            categoryEntity.setChildren(getChildrens(categoryEntity, all));
            return categoryEntity;
        }).sorted((menu1, menu2) -> {
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());
        return children;
    }

}